package com.example.service.impl;

import com.example.DTO.UserReadingStatDTO;
import com.example.mapper.StatMapper;
import com.example.service.CategoryService;
import com.example.service.StatService;
import com.example.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class StatServiceImpl implements StatService {

    @Autowired
    private StatMapper statMapper;

    @Autowired
    private CategoryService categoryService;


    @Override
    public void addLove(Integer articleId) {
        Claims claims = ThreadLocalUtil.get();
        Integer userid = (Integer) claims.get("id");
        Integer categoryId = categoryService.findByArticleId(articleId);
        //获取某一阅读分类的阅读时长
        Integer duration = statMapper.getDuration(userid,categoryId);
        //当前时间
        LocalDateTime now = LocalDateTime.now();
        log.info("用户id：{}，分类id：{}，阅读时长：{}",userid,categoryId,duration);
        //更新分类的阅读时长
        if(duration == null){
            duration = 0;
            duration++;
            statMapper.addDuration(userid,categoryId,duration,now);
        }
        else {
            duration++;
            statMapper.updateDuration(userid,categoryId,duration,now);
        }
    }

    @Override
    public List<UserReadingStatDTO> getUserReadingStat(Integer userid) {
        List<UserReadingStatDTO> list = statMapper.getUserReadingStat(userid);
        int durationTotal = 0;
        for (UserReadingStatDTO userReadingStatDTO : list) {
            durationTotal += userReadingStatDTO.getDuration();
        }
        for (UserReadingStatDTO userReadingStatDTO : list) {
            userReadingStatDTO.setPercent(userReadingStatDTO.getDuration() * 1.0 / durationTotal);
        }
        return list;
    }
}
